﻿using Nest;
using AutoMapper;
using Journeo_backend.Models.Domain;
using Journeo_backend.Configuration;

namespace Journeo_backend.Services.Implementations
{
    public class AttractionService : IAttractionService
    {
        private readonly IElasticClient _elasticClient;
        private readonly ApplicationDbContext _dbContext;
        private readonly IMapper _mapper;
        private readonly RedisService _redisService;
        private readonly JwtHelper _jwtHelper;


        public AttractionService(IElasticClient elasticClient, ApplicationDbContext dbContext, IMapper mapper, RedisService redisService, JwtHelper jwtHelper)
        {
            _elasticClient = elasticClient;
            _dbContext = dbContext;
            _mapper = mapper;
            _redisService = redisService;
            _jwtHelper = jwtHelper;
        }


        public async Task<Response<string>> CreateIndexAsync()
        {
            try
            {
                var isExists = await _elasticClient.Indices.ExistsAsync("attractions");
                if (isExists.Exists)
                {
                    var deleteIndexResponse = await _elasticClient.Indices.DeleteAsync("attractions");
                    if (!deleteIndexResponse.IsValid)
                    {
                        Console.WriteLine("Failed to delete index: " + deleteIndexResponse.DebugInformation);
                        return new Response<string>(Messages.ELASTICSEARCH_DELETE_INDEX_FAILED);
                    }
                }

                var createIndexResponse = await _elasticClient.Indices.CreateAsync("attractions", c => c
                    .Map<Attraction>(m => m
                        .Properties(p => p
                            .Number(n => n.Name("attractionId").Type(NumberType.Long))
                            .Number(n => n.Name("regionId").Type(NumberType.Long))
                            .Text(t => t.Name("name"))
                            .Text(t => t.Name("description"))
                            .Text(t => t.Name("address"))
                            .Text(t => t.Name("image"))
                            .Number(n => n.Name("latitude").Type(NumberType.Float))
                            .Number(n => n.Name("longitude").Type(NumberType.Float))
                            .Text(t => t.Name("priceRange"))
                            .Text(t => t.Name("openingHours"))
                            .Number(n => n.Name("attractionRating").Type(NumberType.Float))
                            .Text(t => t.Name("recommendedVisitTime"))
                            .Text(t => t.Name("recommendedVisitSeason"))
                        )
                    )
                );

                if (!createIndexResponse.IsValid)
                {
                    Console.WriteLine("Failed to create index: " + createIndexResponse.ServerError.Error.Reason);
                }

                return new Response<string>(Messages.ELASTICSEARCH_CREATE_INDEX_SUCCESS);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new Response<string>("error", e.Message));
            }
        }

        // 通过Id获取景点详情
        public async Task<Response<AttractionVO>> GetAttractionDetailById(long id)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new Response<AttractionVO>("error", Messages.USER_NOT_FOUND);
                }

                var attraction = await _dbContext.Attraction.FindAsync(id);
                if (attraction == null)
                {
                    return new Response<AttractionVO>("error", Messages.ATTRACTION_NOT_FOUND);
                }
                var attractionVO = _mapper.Map<AttractionVO>(attraction);

                // 检查当前用户是否点赞
                var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == id && l.UserId == userId);
                if (attractionLike != null)
                {
                    attractionVO.IsLikedByCurrentUser = true;
                }
                return new Response<AttractionVO>(attractionVO);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new Response<AttractionVO>("error", e.Message));
            }
        }

        // 通过地区获取景点
        public async Task<PageResponse<AttractionVO>> GetAttractionsByRegion(int pageNumber, int pageSize, long regionId)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                // 查询是否有地区的父地区为该地区
                var regions = await _dbContext.Region.Where(r => r.ParentId == regionId).Select(r => r.RegionId).ToListAsync();

                var query = _dbContext.Attraction.Where(a => a.RegionId == regionId);
                if (regions.Count != 0)
                {
                    // 如果有子地区，查询子地区的景点，加入到查询结果中
                    query = query.Union(_dbContext.Attraction.Where(a => regions.Contains(a.RegionId)));
                }
                var totalRecords = await query.CountAsync();
                var attractions = await query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0);
            }
        }

        // 通过搜索获取景点
        public async Task<PageResponse<AttractionVO>> GetAttractionsBySearch(int pageNumber, int pageSize, string query)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                var searchResponse = await _elasticClient.SearchAsync<Attraction>(s => s
                    .Query(q => q
                        .Bool(b => b
                            .Should(
                                // 名称匹配，最高权重
                                sh => sh.Match(m => m
                                    .Field(f => f.Name)
                                    .Query(query)
                                    .Boost(3)
                                    .Fuzziness(Fuzziness.Auto)
                                ),
                                // 描述匹配，中等权重
                                sh => sh.Match(m => m
                                    .Field(f => f.Description)
                                    .Query(query)
                                    .Boost(2)
                                    .Fuzziness(Fuzziness.Auto)
                                ),
                                // 地址匹配，较低权重
                                sh => sh.Match(m => m
                                    .Field(f => f.Address)
                                    .Query(query)
                                    .Boost(1)
                                    .Fuzziness(Fuzziness.Auto)
                                )
                            )
                        )
                    )
                    .MinScore(0.1) // 设置最小相关度分数
                    .From((pageNumber - 1) * pageSize)
                    .Size(pageSize)
                );

                var pageAttractions = searchResponse.Documents.ToList();
                var attractionIds = pageAttractions.Select(a => a.AttractionId).ToArray();
                var attractionsFromDb = await GetAttractions(attractionIds);
                var attractionsDict = attractionsFromDb.ToDictionary(a => a.AttractionId);
                var orderedAttractions = attractionIds
                    .Select(id => attractionsDict.GetValueOrDefault(id))
                    .Where(a => a != null)
                    .ToList();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(orderedAttractions);
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(
                    attractionVOs,
                    pageNumber,
                    pageSize,
                    searchResponse.Total
                );
            }
            catch (Exception e)
            {
                return await Task.FromResult(
                    new PageResponse<AttractionVO>("error", e.Message, null, pageNumber, pageSize, 0)
                );
            }
        }

        // 通过评分获取景点
        public async Task<PageResponse<AttractionVO>> GetAttractionsByRating(int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }


                // 获取所有景点并按评分降序排序
                var searchResponse = _dbContext.Attraction.OrderByDescending(a => a.AttractionRating);
                var totalRecords = await searchResponse.CountAsync();
                var attractions = await searchResponse.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0));
            }
        }

        // 通过选择数量获取景点
        public async Task<PageResponse<AttractionVO>> GetAttractionsBySelectCount(int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                // 获取所有景点并按选择数量降序排序
                var searchResponse = _dbContext.Attraction.OrderByDescending(a => a.SelectCount);
                var totalRecords = await searchResponse.CountAsync();
                var attractions = await searchResponse.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0));
            }
        }

        // 通过距离获取景点
        //上下经纬度在2以内
        public async Task<PageResponse<AttractionVO>> GetAttractionsByDistance(int pageNumber, int pageSize, decimal AmapLatitude, decimal AmapLongitude)
        {

            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                // 获取给定经纬度范围：相差不超过 2 度
                decimal AmapLatitudeMin = AmapLatitude - 2;
                decimal AmapLatitudeMax = AmapLatitude + 2;
                decimal AmapLongitudeMin = AmapLongitude - 2;
                decimal AmapLongitudeMax = AmapLongitude + 2;

                // 查询与给定经纬度相差不超过 2 度的景点,根据经纬度计算距离升序排序
                var query = _dbContext.Attraction.Where(a => a.AmapLatitude >= AmapLatitudeMin && a.AmapLatitude <= AmapLatitudeMax && a.AmapLongitude >= AmapLongitudeMin && a.AmapLongitude <= AmapLongitudeMax)
                    .OrderBy(a => Math.Pow((double)(a.AmapLatitude - AmapLatitude), 2) + Math.Pow((double)(a.AmapLongitude - AmapLongitude), 2));

                var totalRecords = await query.CountAsync();

                var attractions = await query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0));
            }
        }

        // 通过热度获取景点
        public async Task<PageResponse<AttractionVO>> GetAttractionsByHot(int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                // 根据热度降序排序（3 * 选择数量 + 点赞数量 + 5 * 评论数量）
                var query = _dbContext.Attraction.OrderByDescending(a => 3 * a.SelectCount + a.LikeCount + 5 * a.CommentCount);
                var totalRecords = await query.CountAsync();
                var attractions = await query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0));
            }
        }


        public async Task<PageResponse<AttractionVO>> GetAttractionsByDistance(long regionId, int pageNumber, int pageSize, decimal AmapLatitude, decimal AmapLongitude)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                var regions = await _dbContext.Region.Where(r => r.ParentId == regionId).Select(r => r.RegionId).ToListAsync();

                // 获取给定经纬度范围：相差不超过 2 度
                decimal AmapLatitudeMin = AmapLatitude - 2;
                decimal AmapLatitudeMax = AmapLatitude + 2;
                decimal AmapLongitudeMin = AmapLongitude - 2;
                decimal AmapLongitudeMax = AmapLongitude + 2;

                // 查询地区Id匹配的，与给定经纬度相差不超过 2 度的景点
                var query = _dbContext.Attraction.Where(a => a.RegionId == regionId && a.AmapLatitude >= AmapLatitudeMin && a.AmapLatitude <= AmapLatitudeMax && a.AmapLongitude >= AmapLongitudeMin && a.AmapLongitude <= AmapLongitudeMax);
                if (regions.Count != 0)
                {
                    // 如果有子地区，查询子地区的景点，加入到查询结果中
                    query = query.Union(_dbContext.Attraction.Where(a => regions.Contains(a.RegionId) && a.AmapLatitude >= AmapLatitudeMin && a.AmapLatitude <= AmapLatitudeMax && a.AmapLongitude >= AmapLongitudeMin && a.AmapLongitude <= AmapLongitudeMax));
                }

                // 根据经纬度计算距离升序排序
                query = query.OrderBy(a => Math.Pow((double)(a.AmapLatitude - AmapLatitude), 2) + Math.Pow((double)(a.AmapLongitude - AmapLongitude), 2));

                var totalRecords = await query.CountAsync();
                var attractions = await query.OrderBy(a => Math.Pow((double)(a.AmapLatitude - AmapLatitude), 2) + Math.Pow((double)(a.AmapLongitude - AmapLongitude), 2)).Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0));
            }
        }

        public async Task<PageResponse<AttractionVO>> GetAttractionsByRating(long regionId, int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                var regions = await _dbContext.Region.Where(r => r.ParentId == regionId).Select(r => r.RegionId).ToListAsync();

                // 查询地区Id匹配的景点
                var query = _dbContext.Attraction.Where(a => a.RegionId == regionId);
                if (regions.Count != 0)
                {
                    // 如果有子地区，查询子地区的景点，加入到查询结果中
                    query = query.Union(_dbContext.Attraction.Where(a => regions.Contains(a.RegionId)));
                }

                // 根据评分降序排序
                query = query.OrderByDescending(a => a.AttractionRating);

                var totalRecords = await query.CountAsync();
                var attractions = await query.OrderByDescending(a => a.AttractionRating).Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, new List<AttractionVO>(), pageNumber, pageSize, 0));
            }
        }

        public async Task<PageResponse<AttractionVO>> GetAttractionsBySelectCount(long regionId, int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                var regions = await _dbContext.Region.Where(r => r.ParentId == regionId).Select(r => r.RegionId).ToListAsync();

                // 查询地区Id匹配的景点
                var query = _dbContext.Attraction.Where(a => a.RegionId == regionId);
                if (regions.Count != 0)
                {
                    // 如果有子地区，查询子地区的景点，加入到查询结果中
                    query = query.Union(_dbContext.Attraction.Where(a => regions.Contains(a.RegionId)));
                }

                // 根据选择数量降序排序
                query = query.OrderByDescending(a => a.SelectCount);

                var totalRecords = await query.CountAsync();
                var attractions = await query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, null, pageNumber, pageSize, 0));
            }
        }

        public async Task<PageResponse<AttractionVO>> GetAttractionsByHot(long regionId, int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionVO>("error", Messages.USER_NOT_FOUND, new List<AttractionVO>(), pageNumber, pageSize, 0);
                }

                var regions = await _dbContext.Region.Where(r => r.ParentId == regionId).Select(r => r.RegionId).ToListAsync();

                // 查询地区Id匹配的景点
                var query = _dbContext.Attraction.Where(a => a.RegionId == regionId);
                if (regions.Count != 0)
                {
                    // 如果有子地区，查询子地区的景点，加入到查询结果中
                    query = query.Union(_dbContext.Attraction.Where(a => regions.Contains(a.RegionId)));
                }

                // 根据热度降序排序（3 * 选择数量 + 点赞数量 + 5 * 评论数量）
                query = query.OrderByDescending(a => 3 * a.SelectCount + a.LikeCount + 5 * a.CommentCount);

                var totalRecords = await query.CountAsync();
                var attractions = await query.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();

                var attractionVOs = _mapper.Map<List<AttractionVO>>(attractions);

                // 检查当前用户是否点赞
                foreach (var attraction in attractionVOs)
                {
                    var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attraction.AttractionId && l.UserId == userId);
                    if (attractionLike != null)
                    {
                        attraction.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionVO>(attractionVOs, pageNumber, pageSize, totalRecords);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionVO>("error", e.Message, null, pageNumber, pageSize, 0));
            }
        }

        public async Task<List<Attraction>> GetAttractions(long[] attractionIds)
        {
            try
            {
                // 先检查数组是否为空
                if (attractionIds == null || attractionIds.Length == 0)
                {
                    return new List<Attraction>();
                }

                // 查询景点
                var attractions = await _dbContext.Attraction.Where(a => attractionIds.Contains(a.AttractionId)).ToListAsync();

                return attractions;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return await Task.FromResult(new List<Attraction>());
            }
        }


        // 点赞景点
        public async Task<Response<string>> LikeAttraction(long userId, long attractionId)
        {
            try
            {
                // 先检查景点及用户是否存在
                var attraction = await _dbContext.Attraction.FirstOrDefaultAsync(a => a.AttractionId == attractionId);
                if (attraction == null)
                {
                    return new Response<string>("error", Messages.ATTRACTION_NOT_FOUND);
                }

                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new Response<string>("error", Messages.USER_NOT_FOUND);
                }

                // 检查是否已经点赞
                var attractionLike = await _dbContext.AttractionLike.FirstOrDefaultAsync(l => l.AttractionId == attractionId && l.UserId == userId);
                if (attractionLike != null)
                {
                    // 已经点赞，取消点赞
                    _dbContext.AttractionLike.Remove(attractionLike);
                    attraction.LikeCount--;
                } else
                {
                    // 未点赞，点赞
                    attractionLike = new AttractionLike
                    {
                        AttractionId = attractionId,
                        UserId = userId,
                        CreatedAt = DateTime.Now
                    };
                    await _dbContext.AttractionLike.AddAsync(attractionLike);
                    attraction.LikeCount++;
                }

                // 更新景点点赞数
                _dbContext.Attraction.Update(attraction);
                await _dbContext.SaveChangesAsync();
                return new Response<string>("success", Messages.ATTRACTION_LIKE_SUCCESS);
            }
            catch (Exception e)
            {
                return new Response<string>("error", e.Message);
            }
        }



        // 创建景点评论
        public async Task<Response<AttractionCommentVO>> CreateAttractionComment(AttractionCommentDTO attractionCommentDTO)
        {
            try
            {
                // 先检查景点及用户是否存在
                var attraction = await _dbContext.Attraction.FirstOrDefaultAsync(a => a.AttractionId == attractionCommentDTO.AttractionId);
                if (attraction == null)
                {
                    return new Response<AttractionCommentVO>("error", Messages.ATTRACTION_NOT_FOUND);
                }

                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == attractionCommentDTO.UserId);
                if (user == null)
                {
                    return new Response<AttractionCommentVO>("error", Messages.USER_NOT_FOUND);
                }

                AttractionComment attractionComment = _mapper.Map<AttractionComment>(attractionCommentDTO);
                attractionComment.CreatedAt = DateTime.Now;
                
                await _dbContext.AttractionComment.AddAsync(attractionComment);

                // 更新景点评论数
                attraction.CommentCount++;
                _dbContext.Attraction.Update(attraction);
                await _dbContext.SaveChangesAsync();

                var attractionCommentVO = _mapper.Map<AttractionCommentVO>(attractionComment);
                return new Response<AttractionCommentVO>(attractionCommentVO);
            }
            catch (Exception e)
            {
                return new Response<AttractionCommentVO>("error", e.Message);
            }
        }

        // 删除景点评论
        public async Task<Response<string>> DeleteAttractionComment(long commentId)
        {
            try
            {
                var attractionComment = await _dbContext.AttractionComment.FirstOrDefaultAsync(c => c.CommentId == commentId);
                if (attractionComment == null)
                {
                    return new Response<string>("error", Messages.ATTRACTION_COMMENT_NOT_FOUND);
                }

                _dbContext.AttractionComment.Remove(attractionComment);

                // 更新景点评论数
                var attraction = await _dbContext.Attraction.FirstOrDefaultAsync(a => a.AttractionId == attractionComment.AttractionId);
                attraction.CommentCount--;
                _dbContext.Attraction.Update(attraction);
                await _dbContext.SaveChangesAsync();
                return new Response<string>("success", Messages.ATTRACTION_COMMENT_DELETE_SUCCESS);
            }
            catch (Exception e)
            {
                return new Response<string>("error", e.Message);
            }
        }

        // 通过景点获取评论
        public async Task<PageResponse<AttractionCommentVO>> GetCommentsByAttraction(long attractionId, int pageNumber, int pageSize)
        {
            try
            {
                long userId = _jwtHelper.GetUserId();
                // 检查userId是否存在
                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new PageResponse<AttractionCommentVO>("error", Messages.USER_NOT_FOUND, new List<AttractionCommentVO>(), pageNumber, pageSize, 0);
                }

                var comments = await _dbContext.AttractionComment.Where(c => c.AttractionId == attractionId).ToListAsync();

                // 根据pageNumber和pageSize返回分页数据
                var pageComments = comments.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();

                var attractionCommentVOs = _mapper.Map<List<AttractionCommentVO>>(pageComments);
                // 检查当前用户是否点赞
                foreach (var comment in attractionCommentVOs)
                {
                    var commentLike = await _dbContext.CommentLike.FirstOrDefaultAsync(l => l.CommentId == comment.CommentId && l.UserId == userId);
                    if (commentLike != null)
                    {
                        comment.IsLikedByCurrentUser = true;
                    }
                }

                return new PageResponse<AttractionCommentVO>(attractionCommentVOs, pageNumber, pageSize, comments.Count);
            }
            catch (Exception e)
            {
                return await Task.FromResult(new PageResponse<AttractionCommentVO>("error", e.Message, new List<AttractionCommentVO>(), pageNumber, pageSize, 0));
            }
        }

        // 上传评论图片
        public async Task<Response<string>> UploadCommentImage(long userId, IFormFile file)
        {
            // 编辑图片url，添加雪花
            string url = $"comment:{userId}_{Guid.NewGuid().ToString()}_{file.FileName}";
            var response = await _redisService.UploadImageAsync(url, file);
            return response;
        }

        // 删除评论图片
        public async Task<Response<string>> DeleteCommentImage(string imageUrl)
        {
            // 直接使用RedisService删除图片
            var response = await _redisService.DeleteImageAsync(imageUrl);
            return response;
        }

        // 点赞评论
        public async Task<Response<string>> LikeComment(long userId, long commentId)
        {
            try
            {
                // 先检查评论及用户是否存在
                var comment = await _dbContext.AttractionComment.FirstOrDefaultAsync(c => c.CommentId == commentId);
                if (comment == null)
                {
                    return new Response<string>("error", Messages.ATTRACTION_COMMENT_NOT_FOUND);
                }

                var user = await _dbContext.User.FirstOrDefaultAsync(u => u.UserId == userId);
                if (user == null)
                {
                    return new Response<string>("error", Messages.USER_NOT_FOUND);
                }

                // 检查是否已经点赞
                var commentLike = await _dbContext.CommentLike.FirstOrDefaultAsync(l => l.CommentId == commentId && l.UserId == userId);
                if (commentLike != null)
                {
                    // 已经点赞，取消点赞
                    _dbContext.CommentLike.Remove(commentLike);
                    comment.LikeCount--;
                }
                else
                {
                    // 未点赞，点赞
                    commentLike = new CommentLike
                    {
                        CommentId = commentId,
                        UserId = userId,
                        CreatedAt = DateTime.Now
                    };
                    await _dbContext.CommentLike.AddAsync(commentLike);
                    comment.LikeCount++;
                }

                // 更新评论点赞数
                _dbContext.AttractionComment.Update(comment);
                await _dbContext.SaveChangesAsync();
                return new Response<string>("success", Messages.ATTRACTION_COMMENT_LIKE_SUCCESS);
            }
            catch (Exception e)
            {
                return new Response<string>("error", e.Message);
            }
        }
    }
}
